package backstage.util.action;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;

import net.sf.json.JSONObject;

import backstage.sys.action.PlatformAction;


public class ClockAction extends PlatformAction{
	
	private String jsonDoc;

	public String execute() throws Exception{
		Map<String,String> map = new HashMap<String, String>();
		
		StringBuffer sb = new StringBuffer();
		URL urltch = new URL("http://weather.yahooapis.com/forecastrss?u=c&p=CHXX0064");
		URLConnection connectiontch = urltch.openConnection();
		connectiontch.connect();
		BufferedReader in = new BufferedReader(new InputStreamReader(connectiontch.getInputStream()));
		String line = null;
		while ((line = in.readLine()) != null) {
			sb.append(line);
		}
		String xmlDoc = sb.toString().replaceAll("\t", "");
		//System.out.println(xmlDoc);
		StringReader read = new StringReader(xmlDoc);
		InputSource source = new InputSource(read);
		SAXBuilder sab = new SAXBuilder();
		Document doc = sab.build(source);
		Element root = doc.getRootElement();
		Element channel = root.getChild("channel");
		List jd = channel.getChildren();
		Element et = null;
		for (int i = 0; i < jd.size(); i++) {
			et = (Element) jd.get(i);
			if ("location".equals(et.getName())) {
				//map.put("city", et.getAttributeValue("city"));
			} else if ("wind".equals(et.getName())) {
				//System.out.println(et.getAttributeValue("chill"));
			} else if ("item".equals(et.getName())) {
				List zjd = et.getChildren();
				for (int j = 0; j < zjd.size(); j++) {
					et = (Element) zjd.get(j);
					if ("condition".equals(et.getName())) {
						map.put("curr_temp", et.getAttributeValue("temp"));
						map.put("curr_icon", et.getAttributeValue("code"));
						map.put("curr_text", et.getAttributeValue("text"));
					}
				}
			}
		}
		//Mist 雾
		map.put("city", "济南");
		JSONObject json = JSONObject.fromObject(map);
		this.jsonDoc = json.toString();
		return "success";
	}

	public String getJsonDoc() {
		return jsonDoc;
	}

	public void setJsonDoc(String jsonDoc) {
		this.jsonDoc = jsonDoc;
	}
}
